<template>
  <div class="blog-create-view">
    <div class="input-area">
      <a-textarea
        v-model:value="value"
        show-count
        :maxlength="100"
        placeholder="请输入评论"
        style="
          background-color: rgba(241, 241, 241, 0.2);
          border-radius: 10px;
          font-size: 15px;
        "
        :auto-size="{ minRows: 2, maxRows: 5 }"
      />
    </div>
    <div class="upload-area">
      <div class="clearfix">
        <a-upload
          v-model:file-list="fileList"
          action=""
          :auto-upload="false"
          list-type="picture-card"
          @preview="handlePreview"
        >
          <div v-if="fileList.length <= 8">
            <plus-outlined />
            <div style="margin-top: 8px">图片上传</div>
          </div>
        </a-upload>
        <a-modal
          :open="previewVisible"
          :title="previewTitle"
          :footer="null"
          @cancel="handleCancel"
        >
          <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>
      </div>
    </div>
    <div class="submit-area">
      <!--      <div class="pks-area">-->
      <!--        <a-dropdown>-->
      <!--          <a class="ant-dropdown-link" @click.prevent>-->
      <!--            {{ privacyText }}-->
      <!--            <DownOutlined />-->
      <!--          </a>-->
      <!--          <template #overlay>-->
      <!--            <a-menu @click="handlePrivacySelect">-->
      <!--              <a-menu-item key="0">-->
      <!--                <a href="javascript:">公开</a>-->
      <!--              </a-menu-item>-->
      <!--              <a-menu-item key="2">-->
      <!--                <a href="javascript:">仅粉丝/好友可见</a>-->
      <!--              </a-menu-item>-->
      <!--              <a-menu-item key="1">-->
      <!--                <a href="javascript:">仅自己可见</a>-->
      <!--              </a-menu-item>-->
      <!--            </a-menu>-->
      <!--          </template>-->
      <!--        </a-dropdown>-->
      <!--      </div>-->
      <div class="button-area">
        <a-button type="primary" @click="handleSubmit">发布</a-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, defineEmits } from "vue";
import { resizeImage } from "@/utils/resizeImage";
const value = ref<string>("");
import { PlusOutlined } from "@ant-design/icons-vue";
import { message, UploadProps } from "ant-design-vue";
import { createBlog, ImageItem } from "@/api/blog";
import type { blogCreateRequest } from "@/api/blog";

function getBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}

const previewVisible = ref(false);
const previewImage = ref("");
const previewTitle = ref("");

const fileList = ref<UploadProps["fileList"]>([]);

const privacyText = ref<string>("公开");
const selectedPrivacy = ref<number>(0);

const handlePrivacySelect = (payload: { key: string }) => {
  const key = payload.key;
  switch (key) {
    case "0":
      privacyText.value = "公开";
      selectedPrivacy.value = 0;
      break;
    case "2":
      privacyText.value = "仅粉丝/好友可见";
      selectedPrivacy.value = 2;
      break;
    case "1":
      privacyText.value = "仅自己可见";
      selectedPrivacy.value = 1;
      break;
    default:
      privacyText.value = "公开";
      selectedPrivacy.value = 0;
  }
};

const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = "";
};
const handlePreview = async (file: UploadProps["fileList"][number]) => {
  // 如果已经有 url 或 preview，则直接使用
  if (file.url || file.preview) {
    previewImage.value = file.url || file.preview;
    previewVisible.value = true;
    previewTitle.value = file.name || "预览图片";
    return;
  }

  // 否则使用 FileReader 读取文件生成 base64 预览
  const reader = new FileReader();
  reader.readAsDataURL(file.originFileObj as File);
  reader.onload = () => {
    file.preview = reader.result as string; // 手动赋值 preview
    previewImage.value = reader.result as string;
    previewVisible.value = true;
    previewTitle.value = file.name || "预览图片";
  };
};

const emit = defineEmits(["blog-created"]);

const handleSubmit = async () => {
  console.log("submit");

  console.log("fileList.value", fileList.value);

  // 构造 blogCreateDTO
  const blogCreateDTO: blogCreateRequest = {
    content: value.value,
  };

  console.log(blogCreateDTO);

  // 构造 images 数组
  const images: ImageItem[] = fileList.value
    .filter((file) => {
      const isValid = file.originFileObj instanceof File;
      if (!isValid) {
        console.warn("⚠️ 找到无效文件:", file);
      }
      return isValid;
    })
    .map((file) => ({
      file: file.originFileObj as File,
    }));

  console.log("图片", images);
  console.log("是否是 File 实例:", images[0]?.file instanceof File);
  console.log("File 对象详情:", images[0]?.file);

  try {
    if (value.value === "" && images.length === 0) {
      message.error("请输入内容或上传图片");
      return;
    }
    await createBlog(value.value, selectedPrivacy.value, images);
    console.log("发布成功");
    message.success("发布成功");
    value.value = "";
    fileList.value = [];
    // 发布成功后
    emit("blog-created");
  } catch (error) {
    console.error("发布失败", error);
  }
};
</script>
<style scoped>
.blog-create-view {
  padding: 20px;
}

/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.submit-area {
  display: flex;
  margin-top: 9px;
  justify-content: right;
  align-items: center;
}

.pks-area {
  margin-right: 10px;
  font-size: 16px;
}

/* 修改上传按钮默认边框颜色为蓝色 */
:deep(.ant-upload-select-picture-card .ant-upload) {
  border-color: #398bfb !important; /* 蓝色边框 */
}

/* 已选中图片的外层卡片也改为蓝色边框 */
:deep(.ant-upload-list-picture-card .ant-upload-list-item) {
  border-color: #398bfb !important;
}

:deep(.ant-tooltip) {
  display: none !important;
}
</style>
